package com.wangdong.wdpermissionlib.permission;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;

import io.reactivex.functions.Consumer;


/**
 * Description: 权限管理
 * @author luyz
 *  2017-04-21 11:21
 */
public class XTPermissionManager {

    private static XTPermissionManager permissionManager;
    private Activity activity;

    private XTPermissionManager() {

    }

    public static XTPermissionManager instance() {
        if (permissionManager == null) {
            synchronized (XTPermissionManager.class) {
                if (permissionManager == null) {
                    permissionManager = new XTPermissionManager();
                }
            }
        }
        return permissionManager;
    }

    public XTPermissionManager with(Activity activity) {
        this.activity = activity;
        return this;
    }

    @SuppressLint("CheckResult")
    public void request(final OnXTPermissionCallback permissionCallback, final String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                this.activity != null &&
                permissionCallback != null) {

            XTPermissions xtPermissions = new XTPermissions(this.activity);

            xtPermissions.requestEach(permissions).subscribe(new Consumer<XTPermission>() {
                @Override
                public void accept(XTPermission permission) throws Exception {
                    if (permission.granted) {
                        permissionCallback.onRequestAllow(permission.name);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        permissionCallback.onRequestRefuse(permission.name);
                    } else {
                        permissionCallback.onRequestNoAsk(permission.name);
                    }
                }
            });
        }else{
            for (String tempItem:permissions) {
                if (permissionCallback!=null) {
                    permissionCallback.onRequestAllow(tempItem);
                }
            }
        }
    }
}
